# -*- coding: utf-8 -*-

import json
from common import credential
from asr import flash_recognizer

# 注意：使用前务必先填写APPID、SECRET_ID、SECRET_KEY，否则会无法运行！！！
APPID = "1323091806"
SECRET_ID = "AKIDmRs69yYdbPzKWXYRI2Yov55ua7ThOxRn"
SECRET_KEY = "Ys45sSq0z6BB1f7MOPCpFSTFm8pOq6A4"
ENGINE_TYPE = "16k_zh"


def recognition(data, format='wav', is_file=True):
    credential_var = credential.Credential(SECRET_ID, SECRET_KEY)
    # 新建FlashRecognizer，一个recognizer可以执行N次识别请求
    recognizer = flash_recognizer.FlashRecognizer(APPID, credential_var)

    # 新建识别请求
    req = flash_recognizer.FlashRecognitionRequest(ENGINE_TYPE)
    req.set_filter_modal(0)
    req.set_filter_punc(0)
    req.set_filter_dirty(0)
    req.set_voice_format(format)
    req.set_word_info(0)
    req.set_convert_num_mode(1)

    # 音频路径
    if is_file:
        with open(data, 'rb') as f:
            data = f.read()
    resultData = recognizer.recognize(req, data)
    resp = json.loads(resultData)
    # print(resp)
    code = resp["code"]
    if code != 0:
        return "Failed to recognize"
            
    return resp["flash_result"][0]["text"]


if __name__ == "__main__":
    file_path = "./recording.m4a"
    content = recognition(file_path, format="m4a")
    # file_path = "test1.m4a"
    # content = recognition(file_path, format="m4a")    
    print(content)
